/*
 * @Author: yixin
 * @Date: 2018-06-22 11:30:31
 * @Last Modified by: yixin
 * @Last Modified time: 2018-07-21 16:32:09
 */
import { applyMiddleware, combineReducers, createStore } from 'redux';
import { createLogger } from 'redux-logger';
import createSagaMiddleware from 'redux-saga';
import { all, fork } from 'redux-saga/effects';

import * as Auth from './auth';
import * as User from './user';

/**
 * controllers 对象
 */
export const controllers = {
  Auth,
  User,
};

/**
 * reducers 列表
 */
export const reducers = {};

/**
 * rootSaga 事件列表
 */
export const sagas = [];

/**
 * 遍历初始 reducers rootSaga 事件列表
 */
let reducersObj = {};
let controllersObj = {};
for (let key in controllers) {
  if ({}.hasOwnProperty.call(controllers, key)) {
    reducersObj = controllers[key].reducers;
    if (reducersObj) {
      for (let keyRedu in reducersObj) {
        if ({}.hasOwnProperty.call(reducersObj, keyRedu)) {
          reducers[`${key}${keyRedu}`] = reducersObj[keyRedu];
        }
      }
    }
    controllersObj = controllers[key].sagas;
    if (controllersObj) {
      for (let keySub in controllersObj) {
        if (keySub && controllersObj[keySub]) {
          sagas.push(controllersObj[keySub]);
        }
      }
    }
  }
}

/**
 * 注册 rootSaga事件
 */
export function* rootSaga() {
  let forkList = [];
  sagas.map((saga, index) => {
    forkList.push(fork(saga));
  });
  console.log('sagas:', sagas);
  yield all(forkList);
}

/**
 * Store
 */
const rootReducer = combineReducers(reducers);
const loggerMiddleware = store => next => (action) => {
  return next(action);
};
const sagaMiddleware = createSagaMiddleware();
let middlewares = [];
// 创建redux-logger中间件
if (__DEV__) {
  const logger = createLogger();
  middlewares.push(logger);
}
// 创建redux-saga中间件
middlewares.push(sagaMiddleware);
const createStoreWithMiddleware = applyMiddleware(...middlewares)(createStore);

export const reduxStore = (initialState, onComplete) => {
  let store;
  store = createStoreWithMiddleware(rootReducer, initialState);
  sagaMiddleware.run(rootSaga);
  // 初始化页面
  onComplete(store);
};
